<template>
  <div class='background'>
<!--    <div class="background">-->
<!--      <img src="../assets/backgroundimg.png"  height="100%" width='100%' alt="" style='float: right;opacity: 0.5'/>-->
<!--    </div>-->

    <ul class="baidu">
      <li><img ref='test' src="../assets/images/2.jpg"></li>
      <li><img src="../assets/images/1.jpg"></li>
      <li><img src="../assets/images/3.jpg"></li>
      <li><img src="../assets/images/4.jpg"></li>
    </ul>

    <div class="avatar_box">
      <img src="../assets/logo.png">
    </div>
    <div class='title'>
      住房补贴系统
    </div>

<!--    <div class="login_box">-->
<!--      &lt;!&ndash; 登录表单区域 &ndash;&gt;-->
<!--      <el-form ref="loginFormRef" :model="loginForm" :rules="loginFormRules" label-width="0px" class="login_form">-->
<!--        &lt;!&ndash; 用户名 &ndash;&gt;-->
<!--        <el-form-item prop="username">-->
<!--          <el-input  v-model="loginForm.username" prefix-icon="iconfont icon-user"></el-input>-->
<!--        </el-form-item>-->
<!--        &lt;!&ndash; 密码 &ndash;&gt;-->
<!--        <el-form-item prop="password" style='margin-top: 30px'>-->
<!--          <el-input v-model="loginForm.password" prefix-icon="iconfont icon-3702mima" type="password"></el-input>-->
<!--        </el-form-item>-->
<!--        &lt;!&ndash; 按钮区域 &ndash;&gt;-->
<!--        <el-form-item class="btns" style='margin-top: 60px'>-->
<!--          <el-button v-if="false" type="primary" @click="login">登录</el-button>-->
<!--          <el-button type="primary" @click="qrcodeLogin">扫码</el-button>-->
<!--          <el-button v-if="false" type="info" @click="resetLoginForm">重置</el-button>-->
<!--          <a v-if="false" style='text-decoration:none; margin-left: 15px' href="javascript:;" @click="changeUser" >↺</a>-->
<!--        </el-form-item>-->
<!--      </el-form>-->
<!--    </div>-->
        <div class="login_box">
          <h3 v-show='!titleIsShow'>扫描二维码登录</h3>
          <span class='title_tip' v-show='titleIsShow'>😅获取二维码失败,请尝试刷新页面!</span>
          <img id="login_success" style="width: 220px; height: 220px; font-size: 20px; color: red" :src='qrcodeInfo.qrcode' alt="加载失败，刷新重试 !"  title="面签宝二维码">
        </div>

<!--    <el-dialog  title="二维码登录" :visible.sync="qrcodeDialogVisible" width="240px">-->
<!--     <img id="login_success" style="width: 180px; height: 180px; font-size: 18px; color: red" :src='qrcodeInfo.qrcode' alt="加载失败，刷新重试 !"  title="二维码">-->
<!--    </el-dialog>-->
  </div>

</template>

<script>
export default {
  data() {
    return {
      // 这是登录表单的数据绑定对象
      loginForm: {
        username: 'jingbanren1',
        password: '123'
      },
      // 这是表单的验证规则对象
      loginFormRules: {
        // 验证用户名是否合法
        username: [
          { required: true, message: '请输入登录名称', trigger: 'blur' },
        ],
        // 验证密码是否合法
        password: [
          { required: true, message: '请输入登录密码', trigger: 'blur' },
        ]
      },
      // 二维码登录响应信息
      qrcodeInfo: {
        qrcode: '',
        verifyId: ''
      },
      qrcodeDialogVisible: false,
      // 二维码失败文字提示是否显示
      titleIsShow: false
    }
  },
  created() {
    this.getQRCode()
  },
  async mounted() {
   // console.log(this.$parent)
    this.addClick();
    this.qrcodeLogin()
  },
  methods: {
   // 二维码获取，同时获取一个验证id以后用
    async getQRCode() {
      try {
        const { data: res } = await this.$http.get('getQRCode')
        if (res.code !== 200) {
          // 直接赋予网络图片地址可以
          // 本地静态资源赋予地址不可以，需要用require来获取
          this.qrcodeInfo.qrcode = require('../assets/images/error.png')
          this.titleIsShow = true
          return this.$message.error('二维码获取失败')
        } else {
          // 请求成功时
          res.data.qrcode = `data:image/png;base64,${res.data.qrcode}`
          this.qrcodeInfo = res.data
        }
      } catch (e) {
        // 请求异常或发生其它错误时，统同样进来
          this.qrcodeInfo.qrcode = require('../assets/images/error.png')
          this.titleIsShow = true
          return this.$message.error('二维码获取失败')
      }
    },
    changeImg() {
      this.$nextTick(async () => {
        let qrcodeImg = await document.getElementById('login_success')
        qrcodeImg.src = require('../assets/images/login_success.jpeg')
      })
    },
    // 二维码登录
    async qrcodeLogin() {
      this.qrcodeDialogVisible = true
      // 第一次访问
      const { data: res } = await this.$http.get('/QRLogin', { params: {
          verifyId: this.qrcodeInfo.verifyId
          // verifyId: 'zfbt:tempLogin:test1'
        }})
      console.log(res)
      if (res.code === 200) {
        this.changeImg()
        // 成功则不再需要定时器
        console.log(res.data)
        window.sessionStorage.setItem('memberToken', res.data.memberToken)
        window.sessionStorage.setItem('username', res.data.username)
        window.sessionStorage.setItem('position', res.data.position)
        window.sessionStorage.setItem('gjjzh', res.data.gjjzh)
        window.sessionStorage.setItem('dwmc', res.data.dwmc)
        this.$message.success('扫码登录成功')

        setTimeout( () => {
          this.$router.push({
            path: '/home',
            query: {
              'menulist':res.data.menuVOList
            }
          })
        },1500)
      } else {
        // 定时器4秒一访问
       const timerId =  setInterval( async () => {
          console.log('访问')
          const { data: res } =  await this.$http.get('/QRLogin', {
            params: {
              // verifyId: this.qrcodeInfo.verifyId
              verifyId: 'zfbt:tempLogin:test1'
            }
          })
          if (res.code === 200) {
            clearInterval(timerId)
            this.changeImg()
            this.$message.success('扫码登录成功')
            window.sessionStorage.setItem('memberToken', res.data.memberToken)
            window.sessionStorage.setItem('username', res.data.username)
            window.sessionStorage.setItem('position', res.data.position)
            window.sessionStorage.setItem('gjjzh', res.data.gjjzh)
            window.sessionStorage.setItem('dwmc', res.data.dwmc)
            window.sessionStorage.setItem('realname', res.data.realname)
            window.sessionStorage.setItem('phoneNumber', res.data.phoneNumber)
            this.$message.success('扫码登录成功')

            setTimeout( () => {
              this.$router.push({
                path: '/home',
                query: {
                  'menulist':res.data.menuVOList
                }
              })
            },1500)

          }
        },4000)
      }
     },
    addClick() {
      var imgs = document.querySelector('.baidu').querySelectorAll('img');

      for (var i = 0; i < imgs.length; i++) {
        imgs[i].onclick = function() {
          // 'url(变量)'，引引加加的方式去写变量
          console.log(this)
          document.getElementsByClassName('background')[0].style.backgroundImage = 'url(' + this.src + ')';
        }
      }
    },
    // 点击重置按钮，重置登录表单
    resetLoginForm() {
      // console.log(this);
      this.$refs.loginFormRef.resetFields()
    },
    /*login() {
      this.$refs.loginFormRef.validate(async valid => {
        console.log('aaa')
        if (!valid) return
        this.$router.push('/home')
      })
    }*/
    login() {
      let that = this
      //let loginForm = JSON.stringify(that.loginForm)
     // console.log(that.loginForm.password)
      this.$http.post('/login',
        {username:this.loginForm.username,
              password:this.loginForm.password
        },
        {emulateJSON:true}).then(res => {
        console.log('登录返回', res)
        if (res.status !== 200) {
          return that.$message.error('登录失败！')
        }
        if(res.data.gjjzh==-1){
          this.$message({
            message: '请输入正确的用户名和密码',
            type: 'warning'
          });
        }
        else{
          that.$message.success('登录成功')
          console.log(res.data)
          window.sessionStorage.setItem('memberToken', res.data.memberToken)
          window.sessionStorage.setItem('username', res.data.username)
          window.sessionStorage.setItem('position', res.data.position)
          window.sessionStorage.setItem('gjjzh', res.data.gjjzh)


          that.$router.push({
            path: '/home',
            query: {
              'menulist':res.data.menuVOList
            }
          })
        }

      })
    },
    // 切换角色用户
    changeUser() {
      this.loginForm.username = 'shenheyuan1'
    }
  }
}
</script>

<style lang="less" scoped>

.login_container {
  background-color: #3F5DC9;
  height: 100%;
}

.login_box {
  width: 400px;
  height: 300px;
  background-color: #fff;
  border-radius: 3px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  text-align: center;

  .title_tip {
    color: red;
    display: block;
    margin: 15px 0 25px;
    font-size: 18px;
    font-weight: bold;
  }
}

.avatar_box {
  height: 90px;
  width: 90px;
  border: 1px solid #eee;
  border-radius: 10%;
  position: absolute;
  left: 35%;
  top: 20%;
  transform: translate(-50%, -50%);
  background-color: #fff;
  img {
    width: 100%;
    height: 100%;
    border-radius: 10%;
    background-color: #eee;
  }
}

.login_form {
  margin-top: 15%;
  bottom: 0;
  width: 100%;
  padding: 0 50px;
  box-sizing: border-box;

}

.background{
  background: url(../assets/images/2.jpg) no-repeat center top;
  //background-color: rgba(63, 93, 201, 0.5);
  width:100%;
  height:100%;  /**宽高100%是为了图片铺满屏幕 */
  //z-index: -1;
  background-size: cover;
  position: absolute;
}

.btns {
  display: flex;
  justify-content: flex-end;
}
.title{
  font-size: 33pt;
  color: #ffffff;
  position: absolute;
  left: 40%;
  top: 16%;
}

ul {
  padding-inline-start: 0;
}
li {
  list-style: none;
}

.baidu {
  overflow: hidden;
  margin: 20px auto;
  background-color: #fff;
  width: 410px;
  padding-top: 3px;
}

.baidu li {
  float: left;
  margin: 0 1px;
  cursor: pointer;
}

.baidu img {
  width: 100px;
}
.demoa {
  cursor: pointer;
}
</style>
